import Vue from 'vue';
import VueRouter from 'vue-router';
import Layout from '@/components/Layout.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Index.vue'),
        meta: { title: '仪表盘', icon: 'el-icon-s-home' }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/user/Index.vue'),
        meta: { title: '用户管理', icon: 'el-icon-user' }
      },
      {
        path: 'order',
        name: 'Order',
        component: () => import('@/views/order/Index.vue'),
        meta: { title: '订单管理', icon: 'el-icon-s-order' }
      },
      {
        path: 'product',
        name: 'Product',
        component: () => import('@/views/product/Index.vue'),
        meta: { title: '商品管理', icon: 'el-icon-goods' }
      },
      {
        path: 'payment',
        name: 'Payment',
        component: () => import('@/views/payment/Index.vue'),
        meta: { title: '支付管理', icon: 'el-icon-bank-card' }
      }
    ]
  }
];

const router = new VueRouter({
  mode: 'hash',
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  
  if (to.path === '/login') {
    next();
  } else {
    if (token) {
      next();
    } else {
      next('/login');
    }
  }
});

export default router;
